home *** CD-ROM | disk | FTP | other *** search
- Path: rcp6.elan.af.mil!rscernix!danpop
- From: danpop@mail.cern.ch (Dan Pop)
- Newsgroups: comp.lang.c
- Subject: Re: memory allocation using malloc and free
- Date: 24 Feb 96 00:43:11 GMT
- Organization: CERN European Lab for Particle Physics
- Message-ID: <danpop.825122591@rscernix>
- References: <4gagll$5rc@bertrand.ccs.carleton.ca> <Pine.SUN.3.91.960222201214.25221B-100000@sunflash.eng.usf.edu>
- NNTP-Posting-Host: ues5.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
-
- In <Pine.SUN.3.91.960222201214.25221B-100000@sunflash.eng.usf.edu> "James Black (CS)" <black@eng.usf.edu> writes:
-
- > I put my comments in the code, but the problem simply is that anything
- >that you pass to a variable to a function the variable in the function is
- >local. If you pass a pointer then the value can change (that the pointer
- >points to), but not the value of the pointer itself. If you want to
- >change what the value is then you pass a pointer to the pointer. Passing
- >a pointer to a pointer will solve your problem, as the returned value of
- >the pointer was probably NULL.
- >
- >On Mon, 19 Feb 1996, Tyler Cope wrote:
-
- #ifdef comp_lang_c
- #define far /* :-) */
- #include <stdlib.h>
- #else
- >> #include <process.h>
- >> #include <alloc.h>
- #endif
- >> #include <stdio.h>
- >
- >> int main(void)
- >> {
- >> void get_mem(unsigned char far *);
- >> void free_mem(unsigned char far *);
- >>
- >> unsigned char far *ptr;
- >>
- >> get_mem(ptr);
- >***** should be get_mem (&ptr);
- >> freemem(ptr);
- >>
- >> return(1);
- >> }
- >>
- >> void get_mem(unsigned char far *fptr)
- >***** void get_mem(unsigned char far **fptr)
- >> {
- >> if ((fptr = (unsigned char far *)malloc(320*200+1)) == NULL)
- >**** if ((*fptr = (unsigned char far *)malloc(320*200+1)) == NULL)
- >> {
- >> printf("Could not allocate enough memory");
- >> exit(1);
- >> }
- >> }
-
- While the proposed fix works (modulo the mistake in the malloc argument),
- it isn't the cleanest solution to the problem. How about:
-
- ptr = get_mem(); /* in main */
-
- and get_mem defined as:
-
- unsigned char far *get_mem(void)
- {
- unsigned char far *fptr = malloc(320U * 200 + 1);
- if (fptr == NULL) {...}
- return fptr;
- }
-
- Always avoid pointers to pointers when this is possible. The resulting
- code would be less error-prone and easier to read and understand.
-
- Note that the expression 320 * 200 + 1 will overflow on DOS (or any other
- platform with 16-bit int's), which will invoke undefined behaviour.
- The easiest fix is to force unsigned arithmetic, as I did in my example.
-
- And the usual remark: don't cast the value returned by malloc. It's not
- necessary and potentially dangerous (like any other unnecessary pointer
- cast).
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-